<template>
    <div class="container">
        <HeaderBar />
        <div class="address_view">
            <div class="container_main between" @click="chooseAddress()">
                <div class="address_view_choose">
                    <img
                        src='../../assets/images/cart/address.png'
                        class="address_view_choose_icon"
                    />
                    <div v-if="deliveryAddrId">
                        <div>{{addressInfo.linkerName}}  {{addressInfo.phone}}</div>
                        <div>{{addressInfo.areaName}}{{addressInfo.address}}</div>
                    </div>
                    <span v-else>请选择收货地址 （选填）</span>
                </div>
                <img
                    src="../../assets/images/cart/right.png"
                    class="address_view_icon"
                />
            </div>
        </div>
        <div class="container_main" style="padding-bottom: 100px">
            <div class="cart_view">
                <div class="cart_view_titles">
                    <div class="action">
                        <img
                            :src="checkAll? require('../../assets/images/cart/check.png') : require('../../assets/images/cart/uncheck.png')"
                            class="checkbox"
                            @click="chooseAll()"
                        />
                    </div>
                    <div class="goodsInfo">商品信息</div>
                    <div class="guige">规格</div>
                    <div class="singleprice">单价</div>
                    <div class="goodsNum">数量</div>
                    <div class="price">金额</div>
                    <div class="actions">操作</div>
                </div>
                <div
                    v-for="item in list"
                    :key="item.id"
                    class="cart_view_item"
                >
                    <div  class="action">
                        <img
                            :src="checkList.indexOf(item.id) > -1 ? require('../../assets/images/cart/check.png') : require('../../assets/images/cart/uncheck.png')"
                            class="checkbox"
                            @click="chooseItem(item.id)"
                        />
                    </div>
                    <div class="goodsInfo cart_view_item_goodsInfo">
                        <img
                            :src="item.mainPic"
                            class="cart_view_item_goodsInfo_img"
                        />
                        <p v-if="item.itemName.length <= 20">{{item.itemName}}</p>
                        <p v-else :title="item.itemName">{{item.itemName.substring(0, 20)}}...</p>
                    </div>
                    <div class="guige">
                        <div class="guige_main">
                            <div  @click="getGoods(item.id, item.itemId)" style="cursor: pointer;">
                                <img
                                    :src="item.show ? require('../../assets/images/cart/up.png') : require('../../assets/images/cart/down.png')"
                                    class="guige_main_icon"
                                />
                                <div class="guige_main_content">
                                    <div
                                        class="guige_main_item"
                                        v-for="(json, key) in item.skuSpecs"
                                        :key="key"
                                    >
                                        {{json.name}}&nbsp;{{json.value}}
                                    </div>
                                </div>
                            </div>
                            <div class="goods_sku" v-if="item.show">
                                <div class="goodsskus" v-for="(item, index) in specs" :key="index">
                                    <div
                                        class="goodsskus-name"
                                    >
                                        {{item.name}}
                                    </div>
                                    <div
                                        class="goodsskus-value"
                                        v-for="json, key in item.values"
                                        :key="json.id"
                                        @click="chooseSku(item.name, json.name, json.id)"
                                        :class="{active: selectSku[item.name].id == json.id}"
                                    >
                                        {{json.name}}
                                    </div>
                                </div>
                                <div class="goodsskus_action" @click="changeGoodsSku">确认</div>
                            </div>
                        </div>
                    </div>
                    <div class="singleprice">¥{{item.price}}</div>
                    <div class="goodsNum">
                        <img
                            src="../../assets/images/cart/reduce.png"
                            class="goodsNum_reduce"
                            @click="reduceItem(item.id, item.volume)"
                        />
                        {{item.volume}}
                        <img
                            src="../../assets/images/cart/add.png"
                            class="goodsNum_add"
                            @click="addItem(item.id, item.volume)"
                        />
                    </div>
                    <div class="price">¥{{item.amount}}</div>
                    <div class="actions" @click="removeItem(item.id)">删除</div>
                </div>
            </div>
        </div>
        <div class="footer_view">
            <div class="container_main between">
                <div class="footer_view_action" @click="chooseAll()">
                    <img
                        :src="checkAll? require('../../assets/images/cart/check.png') : require('../../assets/images/cart/uncheck.png')"
                        class="checkbox"
                    />
                    全选
                </div>
                <div class="footer_view_info">
                    共{{checkList.length}}件商品  合计：
                    <span>¥{{totalPrice}}</span>
                    <div class="footer_view_info_create" @click="createOrder()">生成清单</div>
                </div>
            </div>
        </div>
        <iframe frameborder="0" name="downExcel" style="display:none"></iframe>
    </div>
</template>
<script>
import HeaderBar from '@components/HeaderBar';
import {
    GetCartList,
    postCartDelete,
    PostCartModifyCount,
    PostTradeStart,
    GetGoodsDetail,
    PostCartModifySpec,
    getTradeList,
    GetTradeExport
} from '@api/api';
export default {
    components: {
        HeaderBar,
    },
    data() {
        return {
            checkList: [],
            list: [],
            checkAll: false,
            totalPrice: 0,
            deliveryAddrId: null,
            addressInfo: {},
            detail: {},
            volume: 1,
            selectSku: {},
            sku: [],
            specs: [],
            stock: null,
            price: null,
            itemId: null,
            cartId: null,
            changeSku: {
                itemId: null,
                id: null,
                skuSpecs: [],
            },
            total: 0,
        }
    },
    created () {
        this.getList();
        if (localStorage.getItem('address')) {
            let address = JSON.parse(localStorage.getItem('address'));
            this.addressInfo = address;
            this.deliveryAddrId = address.id;
        }
    },
    methods: {
        // 浮点型加法函数
        accAdd(arg1, arg2) {
            var r1, r2, m
            try {
                r1 = arg1.toString().split('.')[1].length
            } catch (e) {
                r1 = 0
            }
            try {
                r2 = arg2.toString().split('.')[1].length
            } catch (e) {
                r2 = 0
            }
            m = Math.pow(10, Math.max(r1, r2))
            return ((arg1 * m + arg2 * m) / m).toFixed(2)
        },
        // 浮点型乘法
        mul(a, b) {
            var c = 0,
                d = a.toString(),
                e = b.toString()
            try {
                c += d.split('.')[1].length
            } catch (f) {
            }
            try {
                c += e.split('.')[1].length
            } catch (f) {
            }
            return Number(d.replace('.', '')) * Number(e.replace('.', '')) / Math.pow(10, c)
        },
        getGoods(id, itemId) {
            this.cartId = id;
            this.changeSku.id = id;
            GetGoodsDetail({id: itemId})
                .then(res=>{
                    res.data.subPics.unshift(res.data.mainPic);
                    let {
                        sku,
                        specs
                    } = res.data;
                    sku = sku.map(item=>{
                        item.skuId = '';
                        item.specs.forEach(json=>{
                            item.skuId = `${item.skuId}${json.name}-${json.value};`
                        });
                        return item;
                    });
                    let selectSku = {};
                    specs = specs.map((item, index)=>{
                        selectSku[item.name] = '';
                        item.values = [];
                        item.value.forEach((json, key)=>{
                            item.values.push({
                                name: json,
                                id: `${index}-${key}`
                            })
                        });
                        return item;
                    });
                    this.stock = sku[0].stock;
                    this.price = res.data.price;
                    this.selectSku = selectSku;
                    this.specs = specs;
                    this.sku = sku;
                    this.detail = res.data;
                    this.mainPic = res.data.mainPic;
                });
            let {
                list
            } = this;
            list = list.map(item=>{
                if (item.id == id) {
                    item.show = true;
                } else {
                    item.show = false;
                }
                return item;
            });
            this.list = list;
        },
        chooseSku(name, value, key) {
            this.selectSku[name] = {};
            this.selectSku[name].id = key;
            this.selectSku[name].value = `${name}-${value}`;
            let {
                selectSku,
                sku,
                volume
            } = this;
            let itemId = '';
            let skuSpecs = [];
            let keys = Object.keys(selectSku);
            let skuSelected = '';
            let skuSelected1 = '';
            keys.forEach(item=>{
                skuSelected1 = `${skuSelected1}${selectSku[item].value};`
            });
            keys.reverse().forEach(item=>{
                skuSelected = `${skuSelected}${selectSku[item].value};`
            });
            sku.forEach(item=>{
                if (item.skuId == skuSelected || item.skuId == skuSelected1) {
                    itemId = item.itemId;
                    skuSpecs = item.specs;
                }
            });
            this.changeSku.itemId = itemId;
            this.changeSku.skuSpecs = skuSpecs;
        },
        changeGoodsSku() {
            let {
                changeSku
            } = this;
            if (changeSku.length == 0) {
                return false;
            }
            delete changeSku.itemId;
            PostCartModifySpec(changeSku)
                .then(res=>{
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                    this.getList();
                })
        },
        getList() {
            GetCartList()
                .then(res=>{
                    let totalPrice = 0;
                    let {
                        data
                    } = res;
                    data = data.map(item=>{
                        item.checked = false;
                        item.show = false;
                        if (this.checkList.indexOf(item.id) > -1) {
                            totalPrice = this.accAdd(totalPrice, item.amount);
                        }
                        return item;
                    });
                    this.totalPrice = totalPrice;
                    this.list = data;
                });
        },
        removeItem(id) {
            let _this = this;
            _this.$confirm('此操作将永久删除, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                postCartDelete({id: id})
                    .then(res=>{
                        _this.$store.dispatch('cart/getCartNum', {}).then((res) => {
                        }).catch(() => {
                        })  
                        _this.$message({
                            type: 'success',
                            message: '删除成功!'
                        });
                        _this.getList();
                    });
            }).catch(() => {});
        },
        chooseAll() {
            let total = 0;
            let checkList = [];
            let totalPrice = 0;
            let {
                checkAll,
                list
            } = this;
            this.checkAll = !checkAll;
            let num = 0;
            list = list.map(item=>{
                item.checked = !checkAll;
                if (item.checked) {
                    num = num + 1;
                    checkList.push(item.id);
                    total = total + 1;
                    totalPrice = this.accAdd(totalPrice, item.amount);
                }
                return item;
            });
            console.log('num', num)
            this.total = total;
            this.totalPrice = totalPrice;
            this.list = list;
            this.checkList = checkList;
        },
        chooseItem(id) {
            let total = 0;
            let totalPrice = 0;
            let checkList = this.checkList;
            let {
                list
            } = this;
            let all = list.length;
            let chooseNum = 0;
            list.forEach(item=>{
                let index = checkList.indexOf(id);
                if (item.id == id) {
                    if (index != -1) {
                        checkList.splice(index, 1);
                    } else {
                        checkList.push(id);
                        chooseNum ++;
                        total = total + 1;
                        // totalPrice = this.accAdd(totalPrice, item.amount);
                    }
                }
                if(checkList.indexOf(item.id) > -1) {
                    totalPrice = this.accAdd(totalPrice, item.amount);
                }
            });

            console.log('checkList', checkList);
            if (chooseNum == all) {
                this.checkAll = true;
            } else {
                this.checkAll = false;
            }
            this.total = total;
            this.totalPrice = totalPrice;
            this.checkList = checkList;
            this.list = list;
        },
        reduceItem(id, num) {
            let params = {
                id: id,
                volume: num - 1
            }
            if (num > 1) {
                PostCartModifyCount(params)
                    .then(res=> {
                        this.$message({
                            type: 'success',
                            message: '操作成功!'
                        });
                        this.getList();
                    });
            }
            else {
                // postCartDelete({id: id})
                //     .then(res=>{
                //         _this.$store.dispatch('cart/getCartNum', {}).then((res) => {
                //         }).catch(() => {
                //         })  
                //         _this.$message({
                //             type: 'success',
                //             message: '删除成功!'
                //         });
                //         _this.getList();
                //     });
                this.$message({
                    message: '数量已经最小了',
                    type: 'warning'
                });
            }
        },
        addItem(id, num) {
            let params = {
                id: id,
                volume: num + 1
            }
            PostCartModifyCount(params)
                .then(res=> {
                    this.$message({
                        type: 'success',
                        message: '操作成功!'
                    });
                    this.getList();
                });
        },
        createOrder() {
            let {
                deliveryAddrId,
                checkList
            } = this;
            if (checkList.length == 0) {
                this.$message({
                    message: '请选择需要下单的商品!',
                    type: 'warning'
                });
                return false;
            }
            let params = {
                deliveryAddrId: deliveryAddrId,
                cartItemIds: checkList
            }
            PostTradeStart(params)
                .then(res=> {
                    this.$message({
                        message: '操作成功!',
                        type: 'success'
                    });
                    localStorage.removeItem('address');
                    this.addressInfo = {};
                    this.deliveryAddrId = null;
                    this.getList();
                    this.$store.dispatch('cart/getCartNum', {}).then((res) => {
                    }).catch(() => {
                    })
                    this.exportOrder();
                })
        },
        chooseAddress() {
            this.$router.push({path: '/user/address', query: {from: 'cart'}});
        },
        exportOrder() {
            getTradeList({
                status: 1,
                pageNo: 1,
                pageSize: 1,
            }).then(res=>{
                console.log('res', res);
                let id = res.data[0].id;
                GetTradeExport({id: id})
                    .then(res=>{
                        this.download(res.data);
                        this.$message({
                            type: 'success',
                            message: '导出成功!'
                        });
                    });
            })
        },
        download (data) {
            // let link = document.createElement('a');
            // link.style.display = 'none';
            // link.href = data;
            // let timestamp = new Date().getTime();
            // link.download = timestamp + '.xls'
            // document.body.appendChild(link)
            // link.click()
            let iframe = window.frames['downExcel'];
            iframe.location.href = data;
        }
    }
}
</script>
<style>
body {
    background: #fff;
}
</style>
<style scoped>
    @import './index.css';
</style>